package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.Employees;
import com.joint.core.entity.Manage;
import com.joint.core.entity.PersonnelResume;
import com.joint.core.entity.Renew;
import com.joint.core.service.EmployeesService;
import com.joint.core.service.PersonnelResumeService;
import com.joint.core.service.RenewService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxRenewAction extends BaseFlowAction {

    @Resource
    private EmployeesService employeesService;
    @Resource
    private RenewService renewService;
    @Resource
    private DictService dictService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private RemindService remindService;
    @Resource
    private ReadersService readersService;
    @Resource
    private PersonnelResumeService personnelResumeService;

    private Employees employees;
    private Renew renew;
    private String name;
    private String oldPostId;
    private String oldDepId;
    private String oldDepName;
    private String oldPostName;
    private String postId;
    private String renewalStart;
    private String renewalEnd;
    private String startDate;
    private String endDate;
    private BigDecimal renewMoney;
    private String nature;
    private String natureName;
    private Users loginUser;
    private int ifCentralStaff;
    private Users creater;
    private String createDate;
    private String ifPersonnel;
    /**
     * 下一步审批人的Name的集合，用逗号分隔
     */
    private String nextStepApproversName;

    /**
     * 下一步审批人的id的集合，用逗号分隔
     */
    private String nextStepApproversId;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "renew";
    }


    /**
     * 即将到期员工
     * @return
     */
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=renewService.findByPagerAndLimit(true, "renew", pager, params);

        List<Renew> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Renew>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Renew e:eList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",e.getId());
            rMap.put("name",e.getName());
            rMap.put("state",e.getProcessState().value());
            rMap.put("post",e.getRenewPost()==null?"":e.getRenewPost().getName());
            rMap.put("department",e.getDepartment()==null?"":e.getDepartment().getName());
            rMap.put("startDate",DataUtil.DateToString(e.getStartDate(),"yyyy-MM-dd"));
            rMap.put("endDate",DataUtil.DateToString(e.getEndDate(),"yyyy-MM-dd"));
            rMap.put("renewalStart",DataUtil.DateToString(e.getRenewalStart(),"yyyy-MM-dd"));
            rMap.put("renewalEnd",DataUtil.DateToString(e.getRenewalEnd(),"yyyy-MM-dd"));
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){

        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            renew = renewService.get(keyId);
            LogUtil.info("renew"+renew);
            String na =renew.getNature();
            if(na.equals("0")){
                natureName="正式";
            }else if(na.equals("1")){
                natureName="试用";
            }else {
                natureName="聘用";
            }
            numStatus = workflowService.getNumStatus(keyId, loginUser);

        }else {

        }
        return "read";

    }

    public String input(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            renew = renewService.get(keyId);
            String na = renew.getNature();
            if(na.equals("0")){
                natureName="正式";
            }else if(na.equals("1")){
                natureName="试用";
            }else {
                natureName="聘用";
            }
            createDate= DataUtil.DateToString(renew.getCreateDate(),"yyyy-MM-dd");
            creater=renew.getCreater();
            employees=renew.getEmployees();
        }else {
            employees = employeesService.get(parentId);
            LogUtil.info("employees"+employees);
            String na = employees.getNature();
            if(na.equals("0")){
                natureName="正式";
            }else if(na.equals("1")){
                natureName="试用";
            }else {
                natureName="聘用";
            }


            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }

    public void setData(){

        if(StringUtils.isNotEmpty(keyId)){
            renew = renewService.get(keyId);
            employees=renew.getEmployees();
        }else{
            renew = new Renew();
            renew.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(parentId)){
            employees = employeesService.get(parentId);
        }
        if(StringUtils.isNotEmpty(startDate)){
            renew.setStartDate(DataUtil.StringToDate(startDate));
        }
        if(StringUtils.isNotEmpty(endDate)){
            renew.setEndDate(DataUtil.StringToDate(endDate));
        }
        if(StringUtils.isNotEmpty(renewalStart)){
            renew.setRenewalStart(DataUtil.StringToDate(renewalStart));
        }
        if(StringUtils.isNotEmpty(renewalEnd)){
            renew.setRenewalEnd(DataUtil.StringToDate(renewalEnd));
        }
        if(StringUtils.isNotEmpty(oldPostId)){
            renew.setPost(postService.get(oldPostId));
        }
        if(StringUtils.isNotEmpty(oldDepId)){
            renew.setDepartment(departmentService.get(oldDepId));
        }
        if(StringUtils.isNotEmpty(postId)){
            renew.setRenewPost(postService.get(postId));
        }
        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(org.apache.commons.lang.StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    renew.setIfCentralStaff(1);
                }
            }

        }
        renew.setCreater(usersService.getLoginInfo());
        renew.setName(name);
        renew.setRenewMoney(renewMoney);
        renew.setNature(nature);
        renew.setEmployees(employees);
        renew.setNextStepApproversId(nextStepApproversId);
        renew.setNextStepApproversName(nextStepApproversName);
        renew.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(org.apache.commons.lang.StringUtils.isNotEmpty(keyId)){
                renewService.update(renew);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                renewService.save(renew, "renew", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 判断是否为人事专员
     * @return
     */
    public String checkUser(){

        employees = employeesService.get(parentId);
        Department dep = employees.getDep();
        List<Duty> dutys = dutyService.getDutys(dep);
        Map<String,String> data=new HashMap<String, String>();
        loginUser=usersService.getLoginInfo();
        for (Duty duty:dutys){
            Users users = duty.getUsers();
            if(users.equals(loginUser)){
                ifPersonnel="1";
                data.put("ifPersonnel",ifPersonnel);
            }else {
                data.put("ifPersonnel",ifPersonnel);
            }
        }

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list.add(uid.trim());
        }
        ArrayList<String> list1 = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list1.add(uid.trim());
        }

        var2.put("approvers", list);    // 会签人Ids
        var2.put("ifCentralStaff", renew.getIfCentralStaff()); //审批人ids

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                renewService.approve(renew, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId=renewService.commit(renew, "renew", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        Set<Users> usersSet= Sets.newHashSet();
        usersSet=renew.getEmployees().getEmployment().getManage().getChargeUsers();

        //增加归档后读者
        for(Users users:usersSet) {
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("renew");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        for(Users users:usersSet){
            Remind remind = new Remind();
            remind.setUsers(users);
            remind.setBussinessKey("renew");
            remind.setKeyId(keyId);
            remind.setContent("员工续约已归档");
            remindService.save(remind);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批1
     * @return
     */
    public String approve1(){
        renew = renewService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        if(renew.getIfCentralStaff()==1){
            LogUtil.info("ifCentralStaff"+renew.getIfCentralStaff());
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus", 2);
        }

        var1.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                renewService.approve(renew, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 审批2
     * @return
     */
    public String approve2() {
        if(org.apache.commons.lang.StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)) comment="";
        renew = renewService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        PersonnelResume personnelResume = new PersonnelResume();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            renewService.approve(renew, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            if(renew.getEmployees()!=null){
                employees=renew.getEmployees();
                employees.setMoney(renewMoney);
                if(StringUtils.isNotEmpty(renewalStart)){
                    employees.setStartDate(DataUtil.StringToDate(renewalStart));
                }
                if(StringUtils.isNotEmpty(renewalEnd)){
                    employees.setEndDate(DataUtil.StringToDate(renewalEnd));
                }
                Department department=employees.getDep();
                Post post = postService.get(postId);
                Users users=employees.getUsers();
                Set<Duty> dutySet = users.getDutySet();
                for (Duty duty:dutySet){
                    LogUtil.info("duty"+duty);
                    duty.setState(BaseEnum.StateEnum.Delete);
                    dutyService.delete(duty);
                }
                Power power = powerService.getPowerByDepartAndPost(department, post);

                Duty duty=new Duty(users,power,department,post);
                duty.setCompany(usersService.getCompanyByUser());
                duty.setDutyState(EnumManage.DutyState.Default);
                dutyService.save(duty);
                if(StringUtils.isNotEmpty(postId)){
                    employees.setEmpPost(postService.get(postId));
                }

                employeesService.update(employees);

                Users user = employees.getUsers();
                personnelResume.setUsers(user);
                personnelResume.setType("续约申请");
                personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                personnelResumeService.save(personnelResume);

            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 会签
     * @return
     */
    public String approve3() {
        if(org.apache.commons.lang.StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)) comment="";

        renew = renewService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        // var2.put("curDutyId", curDutyId);
        try {
            renewService.approve(renew, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            PersonnelResume personnelResume=new PersonnelResume();
            if(overtask==null){
                Renew entity=renewService.get(keyId);
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                renewService.update(entity);
                if(renew.getEmployees()!=null){
                    employees=renew.getEmployees();
                    employees.setMoney(renewMoney);
                    if(StringUtils.isNotEmpty(renewalStart)){
                        employees.setStartDate(DataUtil.StringToDate(renewalStart));
                    }
                    if(StringUtils.isNotEmpty(renewalEnd)){
                        employees.setEndDate(DataUtil.StringToDate(renewalEnd));
                    }
                    Department department=employees.getDep();
                    Post post = postService.get(postId);
                    Users users=employees.getUsers();
                    Set<Duty> dutySet = users.getDutySet();
                    for (Duty duty:dutySet){
                        LogUtil.info("duty"+duty);
                        duty.setState(BaseEnum.StateEnum.Delete);
                        dutyService.delete(duty);
                    }
                    Power power = powerService.getPowerByDepartAndPost(department, post);
                    Duty duty=new Duty(users,power,department,post);
                    duty.setCompany(usersService.getCompanyByUser());
                    duty.setDutyState(EnumManage.DutyState.Default);
                    dutyService.save(duty);
                    if(StringUtils.isNotEmpty(postId)){
                        employees.setEmpPost(postService.get(postId));
                    }

                    employeesService.update(employees);

                    Users user = employees.getUsers();
                    personnelResume.setUsers(user);
                    personnelResume.setType("续约申请");
                    personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                    personnelResumeService.save(personnelResume);
                }

            }else {

                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){

                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 4);
                }
            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
            renew = renewService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("renew");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(org.apache.commons.lang.StringUtils.isEmpty(comment)) comment="";
            renewService.reject(renew, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
            renew = renewService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("renew");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            renewService.deny(renew, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }
    public Renew getRenew() {
        return renew;
    }

    public void setRenew(Renew renew) {
        this.renew = renew;
    }

    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public BigDecimal getRenewMoney() {
        return renewMoney;
    }

    public void setRenewMoney(BigDecimal renewMoney) {
        this.renewMoney = renewMoney;
    }

    public String getNature() {
        return nature;
    }

    public void setNature(String nature) {
        this.nature = nature;
    }

    public String getNatureName() {
        return natureName;
    }

    public void setNatureName(String natureName) {
        this.natureName = natureName;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getNextStepApproversName() {
        return nextStepApproversName;
    }

    public void setNextStepApproversName(String nextStepApproversName) {
        this.nextStepApproversName = nextStepApproversName;
    }

    public String getNextStepApproversId() {
        return nextStepApproversId;
    }

    public void setNextStepApproversId(String nextStepApproversId) {
        this.nextStepApproversId = nextStepApproversId;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getRenewalStart() {
        return renewalStart;
    }

    public void setRenewalStart(String renewalStart) {
        this.renewalStart = renewalStart;
    }

    public String getRenewalEnd() {
        return renewalEnd;
    }

    public void setRenewalEnd(String renewalEnd) {
        this.renewalEnd = renewalEnd;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public String getIfPersonnel() {
        return ifPersonnel;
    }

    public void setIfPersonnel(String ifPersonnel) {
        this.ifPersonnel = ifPersonnel;
    }

    public String getOldPostId() {
        return oldPostId;
    }

    public void setOldPostId(String oldPostId) {
        this.oldPostId = oldPostId;
    }

    public String getOldDepId() {
        return oldDepId;
    }

    public void setOldDepId(String oldDepId) {
        this.oldDepId = oldDepId;
    }

    public String getOldDepName() {
        return oldDepName;
    }

    public void setOldDepName(String oldDepName) {
        this.oldDepName = oldDepName;
    }

    public String getOldPostName() {
        return oldPostName;
    }

    public void setOldPostName(String oldPostName) {
        this.oldPostName = oldPostName;
    }
}
